<template>
  <div class="login-page">
    <video autoplay loop muted playsinline class="login-video">
      <source src="@/assets/car.mp4" type="video/mp4">
    </video>
    <el-card class="box-card" :style="{boxShadow: 'none'}">
      <div slot="header" class="clearfix">
        <span class="login-title">汽车租凭管理系统</span>
      </div>
      <div class="login-form">
        <el-form :model="form" :rules="loginRules" ref="loginForm">
          <el-form-item prop="userAcct">
            <el-input type="text" v-model="form.userAcct" auto-complete="off" placeholder="请输入账号">
              <template slot="prepend"><i style="font-size:20px" class="el-icon-user"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input type="password" v-model="form.passWord" auto-complete="off" placeholder="请输入密码" :suffix-icon="showPassword ? 'el-icon-eye' : 'el-icon-eye-off'" @suffix-click="showPassword = !showPassword">
              <template slot="prepend"><i style="font-size:20px" class="el-icon-key"></i></template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button style="width:100%;" type="primary" @click="handleLogin" :loading="loading">登录</el-button>
            <el-button style="width:100%;" type="text" @click="showRegisterDialog = true">没有账号？去注册</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-dialog title="注册新用户" :visible.sync="showRegisterDialog">
      <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
        <el-form-item label="客户姓名" prop="clientName">
          <el-input v-model="registerForm.clientName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="clientCard">
          <el-input v-model="registerForm.clientCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="registerForm.address"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="registerForm.confirmPassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showRegisterDialog = false">取消</el-button>
        <el-button type="primary" @click="handleRegister">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'LoginView',
  data() {
    return {
      loading: false,
      form:{
        userAcct: '',
        passWord: ''
      },
      loginRules:{
        userAcct: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        passWord: [
          { required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      showPassword: false,
      showRegisterDialog: false,
      registerForm: {
        clientID: '',
        clientName: '',
        gender: '',
        clientCard: '',
        phone: '',
        address: '',
        password: '',
        confirmPassword: ''
      },
      registerRules: {
        clientName: [
          { required: true, message: '请输入客户姓名', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        clientCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^[0-9]{17}[0-9xX]$/, message: '身份证号格式不正确', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '电话格式不正确', trigger: 'blur'          }
        ],
        address: [
          { required: true, message: '请输入住址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true,message: '请确认密码', trigger: 'blur' },
          { validator: this.validatePassword, trigger: 'blur' },
          { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
        ]
      },
    }
  },
  methods:{
    handleLogin(){
      this.$refs.loginForm.validate().then(()=>{
        this.loading = true;
        const ninthChar = this.form.userAcct.charAt(8);
        let url = '';
        let acctTypeParam = '';
        switch (ninthChar) {
          case '0':
            url = 'http://localhost:8081/clientlogin/login';
            acctTypeParam = 'clientAcct';
            break;
          case '1':
            url = 'http://localhost:8081/salelogin/login';
            acctTypeParam = 'saleAcct';
            break;
          case '2':
            url = 'http://localhost:8081/managerlogin/login';
            acctTypeParam = 'managerAcct';
            break;
          case '3':
            url = 'http://localhost:8081/adminlogin/login';
            acctTypeParam = 'adminAcct';
            break;
          default:
            this.$message({
              message: '无效的账号！',
              type: 'warning'
            });
            this.loading= false;
            return;
        }

        fetch(url + '?' + acctTypeParam + '=' + this.form.userAcct + '&' + acctTypeParam.replace('Acct', 'Pwd') + '=' + this.form.passWord).then(response => {
          if(response.ok){
            response.json().then(data => {
              if(data.code === 0){
                switch (ninthChar) {
                  case '0':
                    this.$router.push({
                      path: '/client/clientView',
                      query: { userAcct: this.form.userAcct }
                    });
                    break;
                  case '1':
                    this.$router.push({
                      path: '/sale/saleView',
                      query: { userAcct: this.form.userAcct }
                    });
                    break;
                  case '2':
                    this.$router.push({
                      path: '/manager/managerView',
                      query: { userAcct: this.form.userAcct }
                    });
                    break;
                  case '3':
                    this.$router.push({
                      path: '/admin/adminView',
                      query: { userAcct: this.form.userAcct }
                    });
                    break;
                }
              } else {
                this.$message({
                  message: data.msg,
                  type: 'warning'
                });
              }
            });
          } else {
            this.$message({
              message: '请求失败！',
              type: 'warning'
            });
          }
          this.loading = false;
        });
      }).catch((()=>{
        this.$message({
          message: '输入错误！',
          type: 'warning'
        });
      }));
    },
    handleRegister(){
      this.$refs.registerForm.validate().then(()=>{
        const data = {
          clientID: '1',
          clientName: this.registerForm.clientName,
          gender: this.registerForm.gender,
          clientCard: this.registerForm.clientCard,
          phone: this.registerForm.phone,
          address: this.registerForm.address,
          password: this.registerForm.password
        }

        /*console.log('password1:', this.registerForm.password);*/
        const passWord = this.registerForm.password;
        axios.post('http://localhost:8081/clientInfo/insert', data).then(response => {
          if (response.data.code === 0) {
            const clientCard = this.registerForm.clientCard;
            axios.get(`http://localhost:8081/clientInfo/select3?clientCard=${clientCard}`).then(response => {
              if (response.data.code === 0) {
                const userAcct = response.data.data;
                /*console.log('password2:', passWord);*/
                this.form.userAcct = userAcct;
                this.form.passWord = passWord;
                axios.post('http://localhost:8081/clientlogin/insert', {
                  clientAcct: userAcct,
                  clientPwd: passWord,
                  clientID: userAcct
                }).then(response => {
                  if (response.data.code === 0) {
                    // 插入成功，自动登录
                    this.form.userAcct = userAcct;
                    this.form.passWord = passWord;
                    this.handleLogin();
                  } else {
                    this.$message.error(response.data.msg);
                  }
                }).catch(error => {
                  console.error(error);
                  this.$message.error('自动登录失败，请稍后重试！');
                });
              } else {
                this.$message.error(response.data.msg);
              }
            }).catch(error => {
              console.error(error);
              this.$message.error('获取客户账号失败，请稍后重试！');
            });
            // 清空注册表单数据
            this.registerForm = {
              clientName: '',
              gender: '',
              clientCard: '',
              phone: '',
              address: '',
              password: '',
              confirmPassword: ''
            }
          // 关闭注册对话框
          this.showRegisterDialog = false;
        } else {
          this.$message({
            message: '注册失败！',
            type: 'warning'
          });
        }
      }).catch(error => {
        console.log(error);
        this.$message({
          message: '注册失败！',
          type: 'warning'
        });
      });
    }).catch((()=>{
      this.$message({
        message: '输入错误！',
        type: 'warning'
      });
    }))
  },
  validatePassword(rule, value, callback) {
    if (value !== this.registerForm.password) {
      callback(new Error('两次输入的密码不一致'));
    } else {
      callback();
    }
  }
}
}
</script>

<style scoped>
.login-page {
  background-image: none;
  background-color: transparent; /* 设置为透明 */
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.login-video {
  position: fixed;
  top: 0;
  left: 0;
  min-width: 100%;
  min-height: 100%;
  z-index: 0; /* 将z-index设置为0，使其低于表单 */
  object-fit: cover;
}
.box-card {
  position: relative;
  z-index: 1; /* 将z-index设置为1，使其高于视频 */
  margin-top: -150px; /* 使表单向上偏移，以使其与标题居中对齐 */
  width: 375px;
}
</style>